import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { ApiResponse } from '@common/interfaces/api-response.interface'
import { PaginationResponse } from '@common/interfaces/pagination-response.interface';
import { Users } from './entities/user.entity'
import { Injectable, ConflictException } from '@nestjs/common';
import { GetUserDto } from './dto/get-user.dto';
import { CreateUserDto } from './dto/create-user.dto';
import { encrypt ,decrypt} from '@utils/crypto.util';
import { log } from 'console';
@Injectable()
export class UsersService {
  private readonly encryptionKey = 'my-secret-key'; // 加密密钥
  constructor(
    @InjectRepository(Users)
    private usersRepository: Repository<Users>
    
  ) { }

  async findUser(getUserDto: GetUserDto): Promise<PaginationResponse<Users>> {
    try {
      const { page, pageSize, username, email } = getUserDto;
      // 使用 QueryBuilder 构建查询
      const query = this.usersRepository.manager
        .createQueryBuilder()
        .select('*') // 选择所有字段
        .from('users', 'users'); // 指定表名和别名

      // 添加模糊查询条件（可选）
      if (username) {
        query.andWhere('users.username LIKE :username', { username: `%${username}%` });
      }
      if (email) {
        query.andWhere('users.email LIKE :email', { email: `%${email}%` });
      }

      // 分页查询并获取总记录数
      const skip = (page - 1) * pageSize;
      const [data, total] = await Promise.all([
        query
          .offset(skip)
          .limit(pageSize)
          .getRawMany(), // 使用 getRawMany 获取原始数据
        query.getCount(), // 使用 getCount 获取总记录数
      ]);

      return {
        code: 200, // 成功状态码
        message: '查询成功', // 成功消息
        data: {
          data,
          total,
          page,
          pageSize,
        },
      };
    } catch (error) {
      console.error('Database error:', error);
      return {
        code: 500, // 失败状态码
        message: '查询失败', // 失败消息
        error: error.message, // 错误详情
      };
    }
  }

  // 检查邮箱和用户名是否已存在
  // 检查邮箱是否已存在
  async checkIfEmailExists(email: string): Promise<void> {
    const existingUser = await this.usersRepository.findOne({ where: { email } });
    if (existingUser) {
      throw new ConflictException('邮箱已存在');
    }
  }

  // 检查用户名是否已存在
  async checkIfUsernameExists(username: string): Promise<void> {
    const existingUser = await this.usersRepository.findOne({ where: { username } });
    if (existingUser) {
      throw new ConflictException('用户名已存在');
    }
  }
  async createUser(createUserDto: CreateUserDto): Promise<ApiResponse<Users>> {
    try {
      // 并行检查邮箱和用户名
      await Promise.all([
        this.checkIfEmailExists(createUserDto.email),
        this.checkIfUsernameExists(createUserDto.username),
      ]);

      // const encryptedPwd = encrypt(createUserDto.password, this.encryptionKey); // 加密邮箱
      // const newUser = this.usersRepository.create({
      //   ...createUserDto,
      //   password: encryptedPwd
      // });
      const newUser = this.usersRepository.create(createUserDto);

      const savedUser = await this.usersRepository.save(newUser);
      return {
        code: 200,
        message: '用户创建成功',
        data: savedUser,
      };
    } catch (error) {
      return {
        code: 500,
        message: '用户创建失败',
        error: error.message,
      };
    }
  }

  async validateUser(username: string, password: string): Promise<Users | null> {
    // 从数据库查找用户
    const user = await this.usersRepository.findOne({ where: { username } });
    
    // 如果找不到用户或密码不匹配，返回 null
    if (!user || !(await decrypt( user.password,this.encryptionKey))) {
      return null;
    }
    
    return user;
  }
} 